package com.feilong.modules.config;

import com.feilong.modules.common.utils.FilterUtil;
import com.feilong.modules.common.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class GateWayFilter implements GlobalFilter, Ordered {


    private static RedisTemplate redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate){
        GateWayFilter.redisTemplate = redisTemplate;
    }

    public static final String TOKEN_KEY = "feilong.login.account:%s";

    /**
     * 白名单。不需要token就能直接调用
     */
    public final static Map<String,String> whiteList = new HashMap();
    static {
        whiteList.put("/user/login", "WhiteList");
        whiteList.put("/auth/getPublicKey", "WhiteList");
    }

    /**
     * 全局过滤器，检查token是否合法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String path = exchange.getRequest().getPath().value();
        // 判断是否在白名单中，是白名单则直接放行
        if (StringUtils.isNotBlank(whiteList.get(path))) {
            return chain.filter(exchange);
        }
        List<String> list = exchange.getRequest().getHeaders().get("x-auth0-token");
        if (CollectionUtils.isEmpty(list)) {
            return FilterUtil.customError(exchange, "账号未登录");
        }
        String token = list.get(0);
        log.info("token is " + token);
        String account = TokenUtil.verifyToken(token);
        String redisToken = (String) redisTemplate.opsForValue().get(String.format(TOKEN_KEY, account));
        if (StringUtils.isBlank(redisToken) || !token.equals(redisToken)){
            return FilterUtil.customError(exchange, "认证时效已过期");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
